package cn.com.w.jdk.thread.pool.threadpool;


import cn.com.w.jdk.thread.pool.config.ThreadPoolConfigYml;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zxl
 * @description 自定义线程池工厂
 */
@Configuration
public class ThreadPoolFactory {

    Logger logger = LoggerFactory.getLogger(ThreadPoolFactory.class);

    private final ThreadPoolConfigYml threadPoolConfigYml;

    @Autowired
    public ThreadPoolFactory(ThreadPoolConfigYml threadPoolConfigYml) {
        System.out.println("执行了有参构造");
        this.threadPoolConfigYml = threadPoolConfigYml;
    }

    /**
     * jdk线程池
     *
     * @return
     */
    @Bean("jdkExector")
    public Executor jdkExector() {
        // 核心线程数
        int corePoolSize = threadPoolConfigYml.getCorePoolSize();
        // 最大线程数
        // 注意：Runtime.getRuntime().availableProcessors()+1 < corePoolSize时会报错。
        int maximumPoolSize = Runtime.getRuntime().availableProcessors() + 1;
        if (corePoolSize >= maximumPoolSize) {
            maximumPoolSize = corePoolSize * 2;
        }

        // 线程活跃时间
        long keepAliveTime = threadPoolConfigYml.getKeepAliveSeconds();
        // 线程活跃时间单位（秒）
        TimeUnit unit = TimeUnit.SECONDS;
        // 队列
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(threadPoolConfigYml.getQueueCapacity());
        // 线程工厂
        ThreadFactory threadFactory = new CustomTreadFactory();
        // 拒绝策略
        RejectedExecutionHandler handler = new CustomRejectedExectionHandler();
        // 自定义线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler);
        return executor;
    }

    /**
     * 自定义的线程工厂
     */
    public static class CustomTreadFactory implements ThreadFactory {

        Logger logger = LoggerFactory.getLogger(CustomTreadFactory.class);

        // 原子int类（保证高并发情况下，保证和递增完整性）
        private final AtomicInteger mThreadNum = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "自定义jdk线程-" + mThreadNum.getAndIncrement());
            logger.info("线程：[{}]被创建。", t.getName());
            return t;
        }
    }

    /**
     * 自定义的拒绝处理策略
     */
    public static class CustomRejectedExectionHandler implements RejectedExecutionHandler {

        Logger logger = LoggerFactory.getLogger(CustomRejectedExectionHandler.class);

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            // 生成日志
            generateLog(r, e);
        }

        private void generateLog(Runnable r, ThreadPoolExecutor e) {
            // 可做日志记录等
            logger.info("线程：[{}]被拒绝处理。", r.toString());
            logger.info("完成任务数[{}]", e.getCompletedTaskCount());
        }
    }

    public static void main(String[] args) {
        System.out.println("cpu核心线程数=" + Runtime.getRuntime().availableProcessors() + 1);
    }

}
